<template>
    <el-form :model="form" :rules="rules" ref="form" label-width="100px"> <el-form-item label="套餐头像"> <el-upload
                class="avatar-uploader" action="https://medicalapp-1317188434.cos.ap-chengdu.myqcloud.com/medical/"
                :auto-upload="false" :show-file-list="false" :on-change="handleChange" list-type="picture-card"> <img
                    v-if="form.image" :src="form.image" class="avatar" width="148px" height="148px" /> <i v-else
                    class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-form-item> 
                    <el-form-item> <el-button type="primary"
                @click="submitForm">提交</el-button> </el-form-item> 
                </el-form>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import axios from 'axios';
export default defineComponent({
    name: 'PackageForm',
    setup() {
        const form = ref({
            name: '', price: '', detail: '', image: '',
        });
        const imgFile = ref<File | null>(null);

        const handleChange = (file: any) => {
            const res = file.name.split('.')[file.name.split('.').length - 1]; const arr = ['jpg', 'png', 'jpeg', 'webp']; if (!arr.includes(res)) { return window.alert('上传头像只能是jpg,png,jpeg,webp格式'); }
            if (file.size / 1024 / 1024 > 2) {
                return window.alert('文件大小不能超过2M');
            }
            form.value.image = URL.createObjectURL(file.raw); imgFile.value = file.raw;
        };
        const submitForm = () => {
            const { value: formData } = new FormData(); if (imgFile.value) {
                formData.append('image', imgFile.value);
                axios.post('http://47.104.168.37:8081/upload/image', {
                    image: imgFile.value
                }).then((res) => {
                    if (res.data.code === 0) {
                        window.alert('图片上传成功');

                        form.value.image = res.data.data; onSubmit();
                    } else {
                        window.alert('图片上传失败');
                    }
                }).catch((err) => {
                    console.log('添加失败', err);
                });
            } else {
                onSubmit();
            }
        };
        const onSubmit = () => {
            void
            axios.post('/api/package', {
                name: form.value.name,
                price: Number(form.value.price),
                detail: form.value.detail,
                image: form.value.image,
            }).then(() => {
                window.alert('提交成功');
            }).catch((err) => {
                window.alert(`提交失败：${err}`);
            });
        };
        return { form, imgFile, rules, handleChange, submitForm, };
    },
}); 
</script>